<script setup lang="ts">
import type { TableColumnData } from '@arco-design/web-vue'
import type { DatePickValue } from '@/components/date-picker'
import dayjs from 'dayjs'
import {
  getCdnNodeSimpleApi,
  getCdnStatisticsWafLogApi,
} from '@/apis/modules/cdn'
import { lastOptions, StrongDatePicker } from '@/components/date-picker'
import { customOptions } from '@/constants/cdn-node'
import { useAppStore } from '@/stores/app'
import { commonTableProps } from '@/utils/table'
import CustomSorting from './components/CustomSorting.vue'
import logDetails from './components/logDetails.vue'
import useConfig from './useConfig'

const { searchSchema, tableColumns } = useConfig()
const appStore = useAppStore()

const queryParams = ref({
  order: 'desc',
  sort: 'time',
  action: 0,
  rep_region: '',
  // module: 0,
  // id: '0',
  start_time: 0,
  end_time: 0,
  ids: [],
})

// const nodeId = ref('')

// const tableData = ref([])
// const loading = ref(false)
// const pagination = ref<{
//   total: number
//   current: number
//   pageSize: number
// }>({
//   current: 1,
//   pageSize: 20,
//   total: 0,
// })

// function run() {
//   loading.value = true
//   const { current, pageSize } = pagination.value
//   debugger
//   getCdnStatisticsWafLogApi({
//     data: queryParams.value,
//     page: {
//       offset: ((current || 1) - 1) * (pageSize || 20),
//       limit: pagination.value.pageSize,
//       sort: 'time',
//       order: orderName.value === 'ascend' ? 'asc' : 'desc',
//     },
//   })
//     .then((res) => {
//       tableData.value = res.list || []
//       loading.value = false
//       pagination.value.total = Number(res.total)
//     })
//     .finally(() => {
//       loading.value = false
//     })
// }

const {
  loading,
  data: tableData,
  pagination,
  run,
} = useListRequest(getCdnStatisticsWafLogApi, {
  params: queryParams,
  buildParams(params) {
    return {
      data: queryParams.value,
      page: {
        offset: params?.offset || 0,
        limit: params?.limit || 20,
        sort: params?.sort,
        order: params?.order,
        // order: orderName.value === 'ascend' ? 'asc' : 'desc',
      },
    }
  },
  immediate: false,
})

const newList = ref<Array<TableColumnData>>([])
// const {
//   visible: editorDialogVisible,
//   open: openEditorDialog,
//   data: editorDialogData,
// } = usePopup()

const { visible: CustomVisible, open: openCustom } = usePopup()

function tableHeader() {
  const NodeLogSort = localStorage.getItem('NodeLogSort')
  if (NodeLogSort) {
    const sortList = JSON.parse(NodeLogSort)
    const resultList = ref([])
    for (let i = 0; i < sortList.length; i++) {
      if (sortList[i].type === true) {
        const obj = tableColumns.find((value) => {
          return value.dataIndex === sortList[i].key
        })
        if (obj) {
          resultList.value.push(obj)
        } else {
          localStorage.setItem('NodeLogSort', '')
        }
      }
    }
    newList.value = resultList.value
  } else {
    newList.value = tableColumns
  }
}
watch(
  () => CustomVisible.value,
  () => {
    tableHeader()
  },
)

const columns = ref<Array<TableColumnData>>([])

watch(
  () => newList.value,
  async () => {
    await nextTick()
    columns.value = buildColumns(newList.value)
  },
)

const { visible: detailVisible, data: detailRecord } = usePopup()
// 配置
function handleDetailConfig(record: any) {
  detailRecord.value = record
  detailVisible.value = true
}

function startDisabledDate(date: Date) {
  const now = dayjs()
  return (
    dayjs(date).isBefore(now.subtract(1, 'month')) || dayjs(date).isAfter(now)
  )
}
function endDisabledDate(date: Date) {
  const now = dayjs()
  return (
    dayjs(date).isBefore(now.subtract(1, 'month')) || dayjs(date).isAfter(now)
  )
}

function handleFilterData(row: [string, string]) {
  nextTick(() => {
    queryParams.value.start_time = Number(row[0])
    queryParams.value.end_time = Number(row[1])
    run()
    // getSafeList(queryParams)
  })
}

const timeState = ref<DatePickValue>([])

function handleRun() {
  queryParams.value.start_time = Number(timeState.value[0])
  queryParams.value.end_time = Number(timeState.value[1])
  run()
}
const TypeOptions = {
  1: 'customRules',
  2: 'speedLimit',
  3: 'whiteList',
}

const router = useRouter()
// 跳转站点管理安全日志
function openWafId(record: any) {
  loading.value = true
  localStorage.setItem('customRulesId', record.waf_id)
  // localStorage.setItem('logModule', record.module)
  router.push({
    name: 'CdnNodeSecurityConfiguration',
    params: { module: TypeOptions[record.module] },
  })
  // getApiSiteDetailApi({ id: record.id })
  //   .then((res) => {
  //     useSiteStore().setSiteInfo(res)
  //     localStorage.setItem('customRulesId', record.waf_id)
  //     localStorage.setItem('logModule', record.module)
  //     router.push({
  //       name: 'SiteConfigureSecurity',
  //       params: { id: record.id }
  //     })
  //   })
  //   .finally(() => {
  //     loading.value = false
  //   })
}

const nodeList = ref<any>([])
// 获取区域
function getNodeList() {
  getCdnNodeSimpleApi({}).then((res) => {
    nodeList.value = res.list || []
  })
}

onMounted(() => {
  queryParams.value.start_time = dayjs(
    dayjs().subtract(60, 'minute').format('YYYY-MM-DD HH:mm:ss'),
  ).unix()
  queryParams.value.end_time = dayjs(
    dayjs().format('YYYY-MM-DD HH:mm:ss'),
  ).unix()

  // run()
  getNodeList()
  tableHeader()
  // run()
})

// function onSorterChange(sort: string, order: string) {
//   orderName.value = order
//   queryParams.value.sort = sort
//   run()
// }

const { createSortChange } = useTable(run, tableData)
const onSorterChange = createSortChange(queryParams)
const MathRandom = ref(1)
function refreshList() {
  MathRandom.value = Math.random()
}
// watch(
//   () => childRef.value?.timeState,
//   () => {
//     run()
//   },
//   { deep: true, immediate: true },
// )
function handleTimeStateSelect(val: DatePickValue) {
  queryParams.value.start_time = Number(val[0])
  queryParams.value.end_time = Number(val[1])
  run()
}
const CountryCodeList = computed<OptionItem[]>(() => {
  return appStore.CountryCode.map(item => ({
    label: item?.name,
    value: item?.code,
  }))
})

function handleClear() {
  queryParams.value.rep_region = ''
}
</script>

<template>
  <main-container
    v-model:pagination="pagination"
    :loading="loading"
    @run="run"
  >
    <div class="mb-4 flex space-x-4">
      <strong-date-picker
        v-model="timeState"
        :math-random="MathRandom"
        :clearable="false"
        :default-last-active="60 * 60"
        :last-options="lastOptions"
        :start-disabled-date="startDisabledDate"
        :end-disabled-date="endDisabledDate"
        @search="handleFilterData"
        @update:model-value="handleTimeStateSelect"
      />
      <!-- <a-select
        v-model="nodeId"
        allow-search
        multiple
        :style="{ width: '136px', height: '32px' }"
        placeholder="请选择节点"
        @change="handleRun"
      >
        <a-option value="">
          全部节点
        </a-option>
        <a-option
          v-for="item in nodeList"
          :key="item.id"
          :value="item.id"
        >
          {{ item.ip }}
        </a-option>
      </a-select> -->
      <a-select
        v-model="queryParams.ids"
        :style="{ width: '220px', height: '32px' }"
        placeholder="全部节点      "
        allow-clear
        multiple
        :max-tag-count="1"
        class="site_select ml-4"
        popup-container-class="log-dropdown-class"
        @change="handleRun"
      >
        <a-option
          v-for="item in nodeList"
          :key="item.id"
          class="h-[28px]"
          :value="item.id"
        >
          {{ item.name }}
        </a-option>
      </a-select>

      <a-select
        v-model="queryParams.action"
        :style="{ width: '136px', height: '32px' }"
        :options="[{ label: '全部执行策略', value: 0 }, ...customOptions]"
        @change="run"
      />

      <a-select
        v-model="queryParams.rep_region"
        allow-clear
        allow-search
        :style="{ width: '136px', height: '32px' }"
        :options="[{ label: '全部地区', value: '' }, ...CountryCodeList]"
        @change="run"
        @clear="handleClear"
      />
      <!-- <a-input-search
        v-model="queryParams.name"
        placeholder="请输入域名搜索"
        class="!w-58"
        @change="run"
      /> -->
      <multiple-condition-search
        v-model="queryParams"
        :schema="searchSchema"
        @search="run"
      />
      <div class="flex-1" />
      <a-button
        class="mr-[-16px] shrink-0 h-[30px]! w-[30px]!"
        type="outline"
        @click="openCustom"
      >
        <template #icon>
          <i-icons-li
            size="4"
            :spin="loading"
          />
        </template>
      </a-button>

      <a-button
        class="ml-auto shrink-0 text-color-1"
        type="outline"
        :disabled="loading"
        @click="refreshList"
      >
        <template #icon>
          <i-icons-refresh :class="{ 'animate-spin': loading }" />
        </template>
      </a-button>
    </div>
    <a-table
      v-bind="commonTableProps"
      :columns="columns"
      :data="tableData"
      @sorter-change="onSorterChange"
    >
      <template #rep_region="{ record }">
        <span v-if="!record.ip && !record.rep_region">-</span>
        <span v-if="record.ip">{{ record.ip }} </span>
        <span v-if="record.rep_region"> ({{ record.rep_region }})</span>
      </template>
      <template #waf_id="{ record }">
        <span
          class="cursor-pointer text-blue-500 hover:underline"
          @click="openWafId(record)"
        >{{ record.waf_id }}</span>
      </template>
      <template #module="{ record }">
        <div
          v-if="record.module === 1"
          class="flex items-center gap-x-1.5"
        >
          自定义规则
        </div>
        <div
          v-else-if="record.module === 2"
          class="flex items-center gap-x-1"
        >
          速率限制
        </div>
        <div
          v-else-if="record.module === 3"
          class="flex items-center gap-x-1"
        >
          白名单
        </div>
      </template>
      <template #action="{ record }">
        <div
          v-if="record.action === 1"
          class="flex items-center gap-x-1.5"
        >
          <i-icons-prevent />
          阻止
        </div>
        <div
          v-if="record.action === 2"
          class="flex items-center gap-x-1.5"
        >
          <i-icons-skip />
          跳过
        </div>
        <div
          v-else-if="record.action === 3"
          class="flex items-center gap-x-1"
        >
          <i-icons-observe />
          观察
        </div>
        <div
          v-else-if="record.action === 4"
          class="flex items-center gap-x-1"
        >
          <i-icons-js />
          JS 质询
        </div>
        <div
          v-else-if="record.action === 5"
          class="flex items-center gap-x-1"
        >
          <i-icons-inquiry />
          交互式质询
        </div>
      </template>
      <template #actions="{ record }">
        <a-link
          :hoverable="false"
          @click="handleDetailConfig(record)"
        >
          <i-icons-eye size="16px" />
        </a-link>
        <!-- <a-link
          :hoverable="false"
          :disabled="record.node_count > 0"
          status="danger"
          class="ml-2"
          @click="handleDelete(record)"
        >
          <i-icons-delete size="16px" / >
        </a-link> -->
      </template>
    </a-table>
  </main-container>

  <custom-sorting
    v-if="CustomVisible"
    v-model:visible="CustomVisible"
  />

  <log-details
    v-if="detailVisible"
    v-model:visible="detailVisible"
    :record="detailRecord"
    @refresh="run"
  />
</template>

<style scoped lang="less">
:deep(.arco-table-th) {
  background-color: #fff !important;
}

:deep(.site_select) {
  height: 32px !important;
  background-color: #fff;

  .arco-select-view-inner {
    white-space: nowrap;
    padding-top: 3px !important;

    .arco-tag {
      white-space: nowrap;
    }

    .arco-select-view-input {
      width: 64px !important;
      height: 20px !important;
    }

    .arco-select-view-input::placeholder {
      color: #86909c;
      font-size: 12px;
    }
  }
}

:deep(.arco-select) {
  .arco-select-dropdown {
    border: 1px solid #f2f3f5;

    .arco-select-option {
      height: 40px;
    }
  }
}

// &-dropdown {
//   @apply !rounded-lg;
//   border: 1px solid #f2f3f5;
//   box-shadow:
//     0px 4px 6px -1px rgba(0, 0, 0, 0.1),
//     0px 2px 4px -2px rgba(0, 0, 0, 0.1) !important;

//   .arco-empty-description {
//     @apply !text-xs;
//   }

//   .arco-select-option {
//     @apply !text-xs !leading-8;
//   }
// }
</style>
